import Vue from 'vue'
import Cookies from 'js-cookie'
import store from '@/store/index.js';

// import main from '../main'
// import bus from "@/api/bus.js"
let token = Cookies.get()
let socket = null;
let lockReconnet = false; //避免重复连接

const wsUrl = 'wss://www.xishidaojia.net/websocket/0';
// const wsUrl = 'ws://47.122.28.87:8666/websocket/0';

let isReconnet = false;
let globalCallback = null,
	sendData = null; //把要发送给socket的数据和处理socket返回数据的回调保存起来

// let data = {
// 	voiceUrl: 5
// }
//export用以登录后调用 避免在登录页面也调用
export let createSocket = url => { //创建socket
	try {
		if ('WebSocket' in window) {
			socket = new WebSocket(url)
		} else if ('MozWebSocket' in window) {
			socket = new MozWebSocket(url)
		}
		Vue.prototype.socket = socket //需要主动关闭的话就可以直接调用this.socket.close()进行关闭，不需要的话这个可以去掉
		initSocket()
	} catch (e) {
		reconnet(url)
	}
}
let sendMsg = (data, callback) => { //发送数据,接收数据
	if (socket.readyState === 1) {
		globalCallback = callback;
		// sendData = data;

		data = JSON.stringify({
			message: 'pong'
		});
		console.log('发送数据', data)
		socket.send(data);
	} else {
		// setTimeout(() => {
		// 	console.log(socket, '等待socket链接成功')
		// 	sendMsg(data, callback)
		// }, 3500)
		return false
	}
	socket.onmessage = ev => {
		callback && callback(ev)
	}
}
let initSocket = () => { //初始化websocket
	socket.onopen = () => {
		sendMsg();
		if (isReconnet) { //执行全局回调函数
			console.log('websocket重新连接了')
			isReconnet = false
		}
		// heartCheck()
		console.log('websocket连接成功')
		// if (store) store.commit('scoket/getWsMsg', data)

		socket.onmessage = (ev) => {
			//存数据 得考虑会不会被覆盖的问题
			let res = JSON.parse(ev.data)
			// console.log('ccccccccccccc', res)
			// if (res.type) store.commit('SET_WS_MSG', res.data)
			if (res) {
				console.log('111', res)
				if (store) store.commit('scoket/getWsMsg', res)
				// res.voiceUrl
				// Vue.prototype.message = res.message;
				// localStorage.setItem('message' , res.message)
				// Vue.prototype.message = res.message;
				// store.dispatch("scoket/changeSetting", {
				// 	type: res.type,
				// 	message: res.message,
				// 	voiceUrl: res.voiceUrl
				// });
			}

		}
	}



	socket.onerror = () => {
		console.log('websocket服务出错了');
		reconnet(wsUrl)
	}

	socket.onclose = () => {
		console.log('websocket服务关闭了');
		reconnet(wsUrl) //防止自动断开
	}
}
let reconnet = url => { //重新连接websock函数
	// //判断有无token
	// if (!token) {
	// 	return false
	// }
	if (lockReconnet)
		return false

	isReconnet = true;
	lockReconnet = true
	setTimeout(() => {
		createSocket(url)
		lockReconnet = false
	}, 4000)
}


// 保持心跳连接
let heartCheck = () => {
	sendMsg();
	setTimeout(function() {
		heartCheck();
		let res = {}
		console.log('fffffffffffffffffff')
		res.voiceUrl = 'https:///image/1748229348083.mp3'
		res.voiceUrl = 'https://xishi-daojia.oss-cn-hangzhou.aliyuncs.com/image/1748229348083.mp3'
		if (store) store.commit('scoket/getWsMsg', res)
	}, 8000);
}
// // <!--webSocket 心跳-->
const heartBeat = {
	timeout: 5000, // 心跳重连时间
	timeoutObj: null, // 定时器
	reset: function() {
		clearTimeout(this.timeoutObj);
		clearTimeout(this.serverTimeoutObj);
		return this;
	},
	start: function() {
		this.timeoutObj = setTimeout(function() {
			console.log('心跳开始');
			sendMsg()
			// this.serverTimeoutObj = setTimeout(function() { //如果超过一定时间还没重置，说明后端主动断开了
			// 	console.log('关闭服务');
			// 	// WS.$ws.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
			// }, this.timeout)
			// if (WS.$ws.readyState === 1) {
			// WS.$ws.send('HeartBeat')
			// }
		}, this.timeout)
	}
}
//避免刷新以后页面没有数据
createSocket(wsUrl)

export default {
	sendMsg
}